package com.wanqing.community.singleSignOn;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;

public class SingleSignOn {

	private Service service = null;
	private Call call = null;
	private String url = "http://sad.263em.com:14003/";
	
	/**
	 * 初始化统一认证的Web Service客户端
	 */
	public SingleSignOn() {
		service = new Service();
		
		try {
			call = (Call)service.createCall();
			call.setTargetEndpointAddress(url);
			
			call.setOperationName(new QName("urn:sad", "authsession"));
			
			call.addParameter("username", XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter("sessionkey", XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter("bindid", XMLType.XSD_STRING, ParameterMode.IN);
			
			call.setReturnType(XMLType.XSD_INT);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 验证身份是否有效
	 * @param username
	 * @param sessionkey
	 * @param bindid
	 * @return
	 */
	public int authSession(String username, String sessionkey, String bindid) {
		int retCode = -1;

		try {
			retCode = (Integer)call.invoke(new java.lang.Object[] {username, sessionkey, bindid});
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		return retCode;
	}
	
	/**
	 * 根据URL进行统一认证
	 */
	public int splitUrl(String url) {
	// 检查输入参数的有效性
	if (url.isEmpty()) {
		return 1;
	}
	
	int mark = url.indexOf("?");
	if (mark <= 0) {
		return 1;
	}
	
	//提取URL参数
	String[] params = url.substring(mark + 1, url.length()).split("&");
	String[] keyValues = null;
	String username = null;
	String sessionkey = null;
	String bindid = null;
			
	int i = 0;
	while (i < params.length) {
		if (params[i].startsWith("user=")) {
			keyValues = params[i].split("=");
			username = keyValues[1];
		}
		else if (params[i].startsWith("sessionkey=")) {
			keyValues = params[i].split("=");
			sessionkey = keyValues[1];
		}
		else if (params[i].startsWith("bindid=")) {
			keyValues = params[i].split("=");
			bindid = keyValues[1];
		}
		
		i ++;
	}

	//调用统一认证接口
	int retCode = authSession(username, sessionkey, bindid);
	return retCode;
	}
}
